from flask import render_template, g, request, current_app, jsonify

from info import user_login_data
from info.models import User
from info.modules.profile import profile_blue
from info.utils.response_code import error_map, RET


@profile_blue.route("/other")
@user_login_data
def profile():
    # 用户本身的对象
    user = g.user
    follow_id = request.args.get("id")
    if not follow_id:
        current_app.aborter(404)

    # 去数据库查询出被关注用户的信息
    try:
        fo_user = User.query.filter(User.id == follow_id).first()
    except Exception as e:
        current_app.logger.error(e)
        current_app.aborter(404)

    if not fo_user:
        current_app.aborter(404)

    fo_user = fo_user.to_dict()
    if fo_user["gender"] == "WOMAN":
        fo_user["gender"] = "男"
    else:
        fo_user["gender"] = "女"

    # 校验一下当前用户是否有关注
    is_follow = False
    try:
        follow = user.followed.filter(User.id == follow_id).first()
    except Exception as e:
        current_app.logger.error(e)
        current_app.aborter(404)

    if follow:
        is_follow = True

    data = {
        "user_info": user.to_dict(),
        "fo_user": fo_user,
        "is_follow": is_follow
    }
    return render_template("news/other.html", data=data)


@profile_blue.route("info")
@user_login_data
def info():
    user = g.user
    # 获取关注用户详情分页数据
    # 1、获取关注详情用户id
    user_id = request.args.get("user_id")
    # 2、获取当前用户页数
    page_id = request.args.get("page_id")

    # 校验一下传入的数据是否有缺失
    if not all([user_id, page_id]):
        current_app.aborter(404)

    try:
        user_id = int(user_id)
        page_id = int(page_id)
    except Exception as e:
        current_app.logger.error(e)
        current_app.aborter(404)

    # 校验一下用户是否存在
    try:
        follow_id = User.query.filter(User.id == user_id).first()
    except Exception as e:
        current_app.logger.error(e)
        current_app.aborter(404)

    if not follow_id:
        current_app.aborter(404)

    news_list = []
    try:
        pagination = follow_id.news_list.paginate(page=page_id, per_page=1, error_out=False)
        follow_new = pagination.items
        follow_page = pagination.page
        follow_pages = pagination.pages
    except Exception as e:
        current_app.logger.error(e)
        current_app.aborter(404)

    for new in follow_new:
        news_list.append(new.to_review_dict())

    return jsonify(errno=RET.OK, errmsg="获取成功",
                   data={"news_list": news_list, "follow_page": follow_page, "follow_pages": follow_pages})
